package com.love.marriage.userCommissionBalance.service.impl;

import com.google.common.collect.Lists;
import com.love.marriage.commissionInfo.service.CommissionInfoService;
import com.love.marriage.commissionInfo.vo.CommissionInfoVo;
import com.love.marriage.common.enums.DefaultAmountTypeEnum;
import com.love.marriage.common.enums.ResultEnum;
import com.love.marriage.common.exceptions.SystemException;
import com.love.marriage.defaultAmountConfig.service.DefaultAmountConfigService;
import com.love.marriage.defaultAmountConfig.vo.DefaultAmountConfigVo;
import com.love.marriage.userCommissionBalance.service.CommissionCommonService;
import com.love.marriage.userCommissionBalance.service.UserCommissionBalanceService;
import com.love.marriage.userCommissionBalance.vo.UserCommissionBalanceVo;
import com.love.marriage.userCommissionWithdrawal.entity.UserCommissionWithdrawal;
import com.love.marriage.userCommissionWithdrawalHistory.service.UserCommissionWithdrawalHistoryService;
import com.love.marriage.userCommissionWithdrawalHistory.vo.UserCommissionWithdrawalHistoryVo;
import com.love.marriage.userInfo.mapper.UserInfoMapper;
import com.love.marriage.userInfo.vo.UserIdentityInfoVo;
import com.love.marriage.userInfo.vo.UserInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class CommissionCommonServiceImpl implements CommissionCommonService {

    private final UserCommissionBalanceService userCommissionBalanceService;

    private final UserCommissionWithdrawalHistoryService userCommissionWithdrawalHistoryService;

    private final CommissionInfoService commissionInfoService;

    private final UserInfoMapper userInfoMapper;

    private final DefaultAmountConfigService defaultAmountConfigService;

    @Override
    public boolean addCommission(Long userId, Long referrerId, BigDecimal amount, Long orderId, String commissionType) {
        // 保存用户回佣信息
        CommissionInfoVo newInfo = new CommissionInfoVo();
        newInfo.setUserId(userId);
        newInfo.setReferrerId(referrerId);
        newInfo.setAmount(amount);
        newInfo.setStatus(1);
        newInfo.setOrderId(orderId);
        newInfo.setCommissionType(commissionType);
        commissionInfoService.addCommissionInfo(newInfo);
        // 更新用户回佣余额表
        UserCommissionBalanceVo userCommissionBalanceVo = userCommissionBalanceService.queryByUserId(referrerId);
        if (userCommissionBalanceVo == null) {
            userCommissionBalanceVo = new UserCommissionBalanceVo();
            userCommissionBalanceVo.setUserId(referrerId);
            userCommissionBalanceVo.setCurrentBalance(amount);
            userCommissionBalanceService.addUserCommissionBalance(userCommissionBalanceVo);
        } else {
            userCommissionBalanceVo.setCurrentBalance(userCommissionBalanceVo.getCurrentBalance().add(amount));
            userCommissionBalanceService.updateUserCommissionBalance(userCommissionBalanceVo);
        }
        return true;
    }

    @Override
    public UserCommissionWithdrawal withdrawalCommission(Long userId, BigDecimal amount, String partnerTradeNo) throws Exception {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new Exception("提现金额不能为空或小于等于0");
        }
        if (amount.compareTo(new BigDecimal("200")) > 0) {
            throw new Exception("提现金额不能超过200元");
        }
        // 校验用户余额是否充足
        UserCommissionBalanceVo userCommissionBalanceVo = userCommissionBalanceService.queryTotalCommissionByUserId(userId);
        if (userCommissionBalanceVo == null || userCommissionBalanceVo.getCurrentBalance().compareTo(amount) < 0) {
            throw new SystemException(ResultEnum.USER_NO_ENOUGH_WITH_BALANCE);
        }
        // 添加回佣记录表中
        UserCommissionWithdrawal userCommissionWithdrawal = new UserCommissionWithdrawal();
        userCommissionWithdrawal.setUserId(userId);
        userCommissionWithdrawal.setWithdrawalAmount(amount);
        userCommissionWithdrawal.setWithdrawalDate(LocalDateTime.now());
        userCommissionWithdrawal.setStatus("PENDING");
        userCommissionWithdrawal.setNotes("用户提现");
        userCommissionWithdrawal.setPartnerTradeNo(partnerTradeNo);
        userCommissionWithdrawal.insert();
//        // 扣除用户回佣余额
//        userCommissionBalanceVo.setCurrentBalance(userCommissionBalanceVo.getCurrentBalance().subtract(amount));
//        userCommissionBalanceService.updateUserCommissionBalance(userCommissionBalanceVo);
        // 保存用户提现记录
        UserCommissionWithdrawalHistoryVo userCommissionWithdrawalHistoryVo = new UserCommissionWithdrawalHistoryVo();
        userCommissionWithdrawalHistoryVo.setUserId(userId);
        userCommissionWithdrawalHistoryVo.setWithdrawalAmount(amount);
        userCommissionWithdrawalHistoryVo.setWithdrawalDate(LocalDateTime.now());
        userCommissionWithdrawalHistoryVo.setStatus("PENDING");
        userCommissionWithdrawalHistoryVo.setNotes("用户提现");
        userCommissionWithdrawalHistoryVo.setPartnerTradeNo(partnerTradeNo);
        userCommissionWithdrawalHistoryService.addUserCommissionWithdrawalHistory(userCommissionWithdrawalHistoryVo);
        return userCommissionWithdrawal;
    }

    @Override
    public boolean addTwoLevelCommission(Long userId, BigDecimal amount, Long orderId, String attach) {
        if (BigDecimal.ZERO.compareTo(amount) >= 0) {
            log.error("用户回佣金额不能小于等于0");
            return false;
        }
        List<UserInfoVo> instrUser = userInfoMapper.queryUserInstrInfo(userId);
        if (instrUser != null && !instrUser.isEmpty() && instrUser.get(0).getIntroUserId() != null) {
            BigDecimal firstRate;
            if ("payBalance".equals(attach)) {
                DefaultAmountConfigVo defaultAmountConfigVo = defaultAmountConfigService.queryDefaultAmountConfigByCode("balance_rate");
                firstRate = defaultAmountConfigVo.getAmount();
            } else {
                UserIdentityInfoVo userIdentityInfoVo = userInfoMapper.queryUserIdentityInfo(instrUser.get(0).getIntroUserId());
                List<String> defaultAmountConfigCodes = Lists.newArrayList(DefaultAmountTypeEnum.FX_FIRST.getCode());
                if (userIdentityInfoVo != null) {
                    if (userIdentityInfoVo.getPartnerFlag() == 1) {
                        defaultAmountConfigCodes.add(userIdentityInfoVo.getPartnerType());
                    }
                    if (userIdentityInfoVo.getMembershipFlag() == 1) {
                        defaultAmountConfigCodes.add("memship_fx_first");
                    }
                    if (userIdentityInfoVo.getMatchmakerFlag() == 1) {
                        defaultAmountConfigCodes.add("matcher_fx_first");
                    }
                }
                // 查询合伙人类型
                List<DefaultAmountConfigVo> defaultAmountConfigVos = defaultAmountConfigService.queryDefaultAmountConfigByCodes(defaultAmountConfigCodes);
                // 查询配置的分成比例，获取回佣比例最高的
                firstRate = defaultAmountConfigVos.stream()
                        .map(DefaultAmountConfigVo::getAmount)
                        .filter(Objects::nonNull)
                        .max(BigDecimal::compareTo)
                        .orElse(new BigDecimal("0.01")); // 默认比例为5%
            }
            addCommission(userId, instrUser.get(0).getIntroUserId(), amount.multiply(firstRate), orderId, "one_level_recharge_amount");
            // 如果推荐列表大于1，则表示有二级分销
            if (instrUser.size() > 1) {
                DefaultAmountConfigVo secondFx = defaultAmountConfigService.queryDefaultAmountConfigByCode(DefaultAmountTypeEnum.FX_SECOND.getCode());
                // 查询配置的分成比例
                BigDecimal secondRate = secondFx == null || secondFx.getAmount() == null ?
                        new BigDecimal("0.1") : secondFx.getAmount();
                addCommission(userId, instrUser.get(1).getIntroUserId(), amount.multiply(secondRate), orderId, "two_level_recharge_amount");
            }
        }
        return true;
    }

    @Override
    public boolean addPartnerCommission(Long userId, BigDecimal amount, Long orderId) {
        if (BigDecimal.ZERO.compareTo(amount) >= 0) {
            log.error("用户回佣金额不能小于等于0");
            return false;
        }
        List<UserInfoVo> instrUser = userInfoMapper.queryUserPartnerInfo(userId);
        if (instrUser == null || instrUser.isEmpty()) {
            return true;
        }
        for (UserInfoVo userInfoVo : instrUser) {
            // 合伙人分成比例
            // 查询默认金额配置
            String defaultCode;
            switch (userInfoVo.getPartnerType()) {
                case "first":
                    defaultCode = DefaultAmountTypeEnum.SX_FIRST.getCode();
                    break;
                case "second":
                    defaultCode = DefaultAmountTypeEnum.SX_SECOND.getCode();
                    break;
                case "third":
                    defaultCode = DefaultAmountTypeEnum.SX_THIRD.getCode();
                    break;
                default:
                    defaultCode = "partner_default";
            }
            DefaultAmountConfigVo defaultAmountConfigVo = defaultAmountConfigService.queryDefaultAmountConfigByCode(defaultCode);
            if (defaultAmountConfigVo != null &&
                    defaultAmountConfigVo.getAmount() != null &&
                    BigDecimal.ZERO.compareTo(defaultAmountConfigVo.getAmount()) <= 0) {
                BigDecimal rate = defaultAmountConfigVo.getAmount();
                addCommission(userId, userInfoVo.getIntroUserId(), amount.multiply(rate), orderId, "partner");
            }
        }
        return true;
    }
}
